package com.jp.knowledge.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.util.Util;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.NetLogActivity;
import com.jp.knowledge.activity.WalletActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.dialog.SelectDialog;
import com.jp.knowledge.logic.InviteFriendsLogic;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.logic.ShareLogic;
import com.jp.knowledge.model.FoundItem;
import com.jp.knowledge.model.InteractDataModel;
import com.jp.knowledge.model.InviteFriendsModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.AppSettingActivity;
import com.jp.knowledge.my.activity.CollectionActivity;
import com.jp.knowledge.my.activity.FeedbackActivity;
import com.jp.knowledge.my.activity.HelpActivity;
import com.jp.knowledge.my.activity.IntegralActivity;
import com.jp.knowledge.my.activity.MessageActivity;
import com.jp.knowledge.my.activity.MessageDetailActivity;
import com.jp.knowledge.my.activity.MyCommentsActivity;
import com.jp.knowledge.my.activity.MyRoleActivity;
import com.jp.knowledge.my.activity.OrderActivity;
import com.jp.knowledge.my.activity.OrganizeActivity;
import com.jp.knowledge.my.activity.UserSettingActivity;
import com.jp.knowledge.my.activity.VipActivity;
import com.jp.knowledge.my.activity.UserVipActivityOld;
import com.jp.knowledge.my.activity.VipBuyActivity;
import com.jp.knowledge.my.adapter.MyDataAdapter;
import com.jp.knowledge.my.adapter.MyMoreAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.business.MyMainBusiness;
import com.jp.knowledge.my.model.ActiveDataModel;
import com.jp.knowledge.my.model.OptionSelectModel;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.service.LatestStateService;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.QRCodeUtils;
import com.jp.knowledge.util.ShareBuilder;
import com.jp.knowledge.view.FoundItemView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.jp.knowledge.util.UrlManager.SHARE_BASE_URL;

/**
 * Created by jiayen on 16/9/28.
 */
public class MyFragment extends BaseFragment implements OnClickListener {

	//退出登录
	public static final int EXIT_LOGIN_CODE = 0x0000000000111;
	//登录
	public static final int LOGIN_CODE = 0x0000000000112;

	public static final int SWITCH_ORGANIZE_CODE = 0x0000000000113;

	public static final int USER_DATA_SETTING = 0x0000000000114;

	private View mView;

	private MyMainBusiness mBusiness = new MyMainBusiness();

	private UserData userData;
	private LocalBroadCast localBroadCast;
	private LocalBroadcastManager localBroadcastManager;

	private boolean isLogin = false;

	/**
	 * 编辑个人信息
	 */
	@ViewInject(R.id.edit_info_btn)
	private TextView editInfoBtn;

	/**
	 * 头像
	 **/
	@ViewInject(R.id.head_photo)
	private ImageView headPhoto;

	/**
	 * 点击登录按钮
	 */
	@ViewInject(R.id.login_btn)
	private TextView loginBtn;

	/**
	 * 成为vip按钮
	 */
	@ViewInject(R.id.vip_btn)
	private TextView vipBtn;

	/**
	 * vip帮助按钮
	 */
	@ViewInject(R.id.vip_hlep)
	private TextView vipHelp;

	/**
	 * 消息等布局
	 **/
	@ViewInject(R.id.msg_layout)
	private RecyclerView msgLayout;

	/**
	 * 各栏目根布局
	 **/
	@ViewInject(R.id.cloumn_layout)
	private LinearLayout columnLayout;

	/***
	 * 登录用户信息布局
	 **/
	@ViewInject(R.id.user_info_layout)
	private RelativeLayout userInfoLayout;

	/**
	 * 用户名称
	 */
	@ViewInject(R.id.user_name)
	private TextView userName;

	/**
	 * 会员识别等级
	 */
	@ViewInject(R.id.vip_tip)
	private TextView vipTip;

	/**
	 * 会员识别等级
	 */
	@ViewInject(R.id.vip_time)
	private TextView vipTime;

	/**
	 * 消息小红点
	 */
	@ViewInject(R.id.messageDot)
	private View messageDot;

	/***
	 * 组织相关view
	 */
	private RecyclerView organaView;


	private MyDataAdapter mDataAdapter;
	private List<ActiveDataModel> modelList;

	private MyMoreAdapter mMoreAdapter;

	private List<OptionSelectModel> attestationRvData;

	private InviteFriendsModel inviteFriendsModel;
	private InviteFriendsLogic inviteFriendsLogic;
	private InviteFriendsLogic.ReadDataCallback readDataCallback;

	private ShareBuilder shareBuilder;
	private ImageView qrCodeImg;
	private Dialog qrCodeDialog;
	private SelectDialog shareSelectDialog;


	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.activity_my_main, null);
		x.view().inject(this, mView);
		initHead(mView);
		init();
		return mView;
	}

	/**
	 * 初始化
	 */
	private void init() {

		userData = application.getUserData();
		organaView = createOrgnaView();

		initHead(mView);
		topName.setText("我的");
		rightBtn.setText("编辑");
		rightBtn.setVisibility(View.GONE);
		rightBtn.setOnClickListener(this);
		rightIcon.setVisibility(View.VISIBLE);
		rightIcon.setImageResource(R.mipmap.mynews);
		rightIcon.setOnClickListener(this);
		//初始化各控件点击事件
		editInfoBtn.setOnClickListener(this);
		headPhoto.setOnClickListener(this);
		loginBtn.setOnClickListener(this);
		vipBtn.setOnClickListener(this);
		vipHelp.setOnClickListener(this);
		headPhoto.setOnClickListener(this);

		//初始化消息栏
		initDataRv(mBusiness.getActiveData(getActiveIndex(true), userData));

		//初始化底部各栏目
		initCloumnView();
		initBroadCast();
		initUserData(isLogin);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            View topBar = mView.findViewById(R.id.top_bar);
//            int statusBarHeight = 0;
//            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
//            if (resourceId > 0)
//                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
//            topBar.setPadding(0, statusBarHeight, 0, 0);
//        }

		readDataCallback = new InviteFriendsLogic.ReadDataCallback() {
			@Override
			public void readFinish(InviteFriendsModel data) {
				inviteFriendsModel = data;
			}
		};
		inviteFriendsLogic = new InviteFriendsLogic(mContext);
	}

	/**
	 * 拼接公司数据
	 *
	 * @param userData
	 * @return
	 */
	private String getOrganization(UserData userData) {
		List<OrganizaModel> companys = userData.getCompanyList();

		if (companys == null) return "";
		StringBuilder sb = new StringBuilder();
		for (OrganizaModel company : companys) {
			sb.append(",").append(company.getCompanyName());
		}
		if (sb.length() > 1)
			return companys.size() + "家(" + sb.substring(1) + ")";
		return "";
	}

	/**
	 * 创建组织view
	 *
	 * @return
	 */
	private RecyclerView createOrgnaView() {
		RecyclerView orgnazaView = new RecyclerView(mContext);
		orgnazaView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
		return orgnazaView;
	}

	/**
	 * 初始化本地广播通知
	 */
	private void initBroadCast() {
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
		localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
			@Override
			public void done(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(LocalBroadCast.GET_LOGIN_INFO)) {//登录
					isLogin = true;
					initUserData(isLogin);
					initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
				} else if (action.equals(LocalBroadCast.COMPANY_JOIN) || action.equals(LocalBroadCast.COMPANY_EXIT)) {//加入和退出公司广播
					new PersonLogic(mContext).getUserData();//重新刷新个人信息
				} else if (action.equals(LocalBroadCast.USER_DATA_CHANGE)) {// 用户数据发生改变
					initUserData(true);
					initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
				} else if (action.equals(LocalBroadCast.LOGOUT_SUCCESS_BROD)) {// 退出登陆
					isLogin = false;
					initUserData(isLogin);
					initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
					// 隔300毫秒刷新数据
					mView.postDelayed(new Runnable() {
						@Override
						public void run() {
							new PersonLogic(mContext).getUserData();//重新刷新个人信息
						}
					}, 300);
				} else if(action.equals(LocalBroadCast.GET_INTERACT_DATA_CODE)){
					InteractDataModel dataModel = LatestStateService.getInteractDataModel();
					messageDot.setVisibility((dataModel == null || dataModel.getSystemMsgCount() == 0) ? View.GONE : View.VISIBLE);
				}
			}
		});
		IntentFilter intent = new IntentFilter();
		intent.addAction(LocalBroadCast.GET_LOGIN_INFO);
		intent.addAction(LocalBroadCast.USER_DATA_CHANGE);
		intent.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
		intent.addAction(LocalBroadCast.GET_INTERACT_DATA_CODE);
		localBroadcastManager.registerReceiver(localBroadCast, intent);
	}

	@Override
	public void onResume() {
//		new PersonLogic(mContext).getUserData();//重新刷新个人信息
		inviteFriendsLogic.readInviteData(readDataCallback);
		super.onResume();
	}

	/**
	 * 初始化用户信息
	 *
	 * @param isLogin
	 */
	private void initUserData(boolean isLogin) {
		try {

			userData = application.getUserData();
			if (userData == null) {
				isLogin = false;
			} else if (userData.getIsLogin() == 1) isLogin = true;
			else isLogin = false;
			if (isLogin) {
				editInfoBtn.setVisibility(View.VISIBLE);
				organaView.setVisibility(View.VISIBLE);
				userName.setText(userData.getUsername());
				if (userData.getBindWeixin() == 1)
					userName.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.wechat), null);
				else
					userName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
				userInfoLayout.setVisibility(View.VISIBLE);
				loginBtn.setVisibility(View.GONE);
				vipTip.setText(userData.getGradeName());
				if (userData.getIsVip() == 1) {              // 是会员
					vipTime.setText("(" + userData.getVipDays() + "天后过期)");
					vipTime.setVisibility(userData.getVipDays() < 30 ? View.VISIBLE : View.GONE);
					vipBtn.setText("会员特权");
					vipBtn.setTextColor(getResources().getColor(R.color.white));
					vipBtn.setBackground(getResources().getDrawable(R.drawable.btn_blue_end));
					vipHelp.setVisibility(View.GONE);
				} else if (userData.getIsVip() == 2) {        // 会员过期
					vipTime.setVisibility(View.VISIBLE);
					vipTime.setText("(会员已过期)");
					vipBtn.setText("续费VIP");
					vipBtn.setTextColor(getResources().getColor(R.color.white));
					vipBtn.setBackground(getResources().getDrawable(R.drawable.btn_blue_end));
					vipHelp.setVisibility(View.VISIBLE);
				} else {
					vipTime.setVisibility(View.GONE);
					vipBtn.setText("成为VIP");
					vipBtn.setTextColor(getResources().getColor(R.color.white));
					vipBtn.setBackground(getResources().getDrawable(R.drawable.btn_blue_end));
					vipHelp.setVisibility(View.VISIBLE);
				}
				//            topName.setText(userData.getUsername());
				if (Util.isOnMainThread()) {
					if (userData.getPortrait() != null && userData.getPortrait().contains("pic.jp580.com"))
						ImageLoadUtil.loadCircle(mContext, userData.getPortrait() + "?imageView2/2/w/100/h/100/interlace/1/format/jpg", headPhoto);
					else
						ImageLoadUtil.loadCircle(mContext, userData.getPortrait(), headPhoto);

				}
				//初始化登录状态下的 组织状态
				//            initAttestationRv(mBusiness.getAttestationItems(userData));
				attestationRvData = mBusiness.getAttestationItems(userData);
				if (mMoreAdapter == null) {
					initAttestationRv();
				} else {
					mMoreAdapter.updateAdapter(attestationRvData);
				}

				try {
					FoundItemView view = (FoundItemView) columnLayout.getChildAt(1);
					view.setDescriptionColor(R.color.font_gray_deep);
					view.setDescription(getOrganization(userData));
				} catch (Exception e) {
					e.printStackTrace();
				}
				String[] values = new String[]{"0", "0", "0", String.format("%.2f", userData.getTotalAmount() / 100.00) + "", "0", "0"};
				if (modelList != null && mDataAdapter != null) {
					int size = modelList.size();
					for (int i = 0; i < size; i++) {
						ActiveDataModel model = modelList.get(i);
						model.value = values[i];
					}

					mDataAdapter.updateAdapter(modelList);
				}
			} else {
				editInfoBtn.setVisibility(View.GONE);
				try {
					FoundItemView view = (FoundItemView) columnLayout.getChildAt(1);
					view.setDescriptionColor(R.color.font_gray_deep);
					view.setDescription("");
				} catch (Exception e) {
					e.printStackTrace();
				}
				organaView.setVisibility(View.GONE);
				headPhoto.setImageResource(R.mipmap.headportrait);
				userInfoLayout.setVisibility(View.GONE);
				loginBtn.setVisibility(View.VISIBLE);
				topName.setText("我的");

				vipBtn.setText("成为VIP");
				vipHelp.setVisibility(View.VISIBLE);
			}

		} catch (Exception e) {
			L.e(e.getMessage());
		}
	}

	/***
	 * 去到登录页面
	 */
	private void toLoginActivity() {
		startActivity(new Intent(mContext, LoginActivity.class));
	}

	/**
	 * 初始化栏目类view
	 */
	private void initCloumnView() {
		if (userData == null) userData = application.getUserData();
		String[] names = new String[]{"所属组织", "任务大厅", "我的点评", "意见反馈", "专属客服", "邀请好友", "帮助", "设置"};
		int[] resIds = new int[]{R.mipmap.subordinateorg,
				R.mipmap.missionhall,
				R.mipmap.dianping,
				R.mipmap.feedback,
				R.mipmap.customer,
				R.mipmap.invitefriends,
				R.mipmap.help,
				R.mipmap.set
		};
		int size = names.length;
		for (int i = 0; i < size; i++) {
			FoundItem item = new FoundItem();
			item.setResId(resIds[i]);
			item.setName(names[i]);
			item.setShowPhoto(true);
			item.setShowTip(true);
			item.setDescriptionColor(R.color.red);

			if (i == 0 && userData != null) {
				item.setDescriton(getOrganization(userData));
			}

			if (i == 1) {
				columnLayout.addView(createBackGroundView(2));
				item.setDescriton("用知识获取回报");
				columnLayout.addView(organaView);
			}
			if (i == 2) {
//                item.setDescriton("点评送大礼");
			}
			if (i == 5) {
//                item.setDescriton("邀请送大礼");
			}

			if (i == 1 || i == 4) {
				columnLayout.addView(createBackGroundView(30));
			} else if (i != 2 && i != 5) {
				columnLayout.addView(createBackGroundView(2));
			}

			FoundItemView view = new FoundItemView(mContext);
			view.setTag(i);
			view.setOnClickListener(CloumnClick);
			view.setItem(item);
			columnLayout.addView(view);

			if (i == 1 || i == 4) {
				view.setVisibility(View.GONE);
			}
		}

	}


	/**
	 * 初始化组织各个状态
	 */
	private void initAttestationRv() {
		if (attestationRvData != null) {
			organaView.setHasFixedSize(true);
			GridLayoutManager layoutManager = new GridLayoutManager(mContext, 4, LinearLayoutManager.VERTICAL, false);
			organaView.setLayoutManager(layoutManager);
			mMoreAdapter = new MyMoreAdapter(mContext, new ArrayList<OptionSelectModel>());
			mMoreAdapter.updateAdapter(attestationRvData);
			mMoreAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
				@Override
				public void itemSelect(int position) {
					try {
						Intent intent = new Intent(mContext, Class.forName(attestationRvData.get(position).mValue));
						startActivity(intent);
					} catch (Exception e) {
						return;
					}
				}
			});
			organaView.setAdapter(mMoreAdapter);
		} else {
			ToasUtil.toast(mContext, "栏目数据为空");
		}
	}


	/**
	 * 定义点击事件
	 */
	private OnClickListener CloumnClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			int flag = (int) v.getTag();
			switch (flag) {
				case 0://所属组织
//                    if (!application.isLogin()) {
//                        toLoginActivity();
//                    } else {
//                        startActivityForResult(new Intent(context, OrganizeActivity.class),
//                                SWITCH_ORGANIZE_CODE);
//                    }
					// 现在可以不登陆切换组织了
					startActivityForResult(new Intent(mContext, OrganizeActivity.class),
							SWITCH_ORGANIZE_CODE);
					break;
				case 1://竞品说角色
					startActivity(new Intent(mContext, MyRoleActivity.class));
					break;
				case 2://点评
					startActivity(new Intent(mContext, MyCommentsActivity.class));
					break;
				case 5://邀请好友
					shareClick();
					break;
				case 4://专属客服
					break;
				case 3://意见反馈
					startActivity(new Intent(mContext, FeedbackActivity.class));
					break;
				case 6://帮助
//                    showNetLog();
					startActivity(new Intent(mContext, HelpActivity.class));
					break;
				case 7://设置
//                    startActivityForResult(new Intent(mContext, SetActivity.class), EXIT_LOGIN_CODE);
					startActivityForResult(new Intent(mContext, AppSettingActivity.class), EXIT_LOGIN_CODE);
					break;
				default:
					break;
			}
		}


	};

	private void shareClick(){
		if(shareSelectDialog == null){
			shareSelectDialog = new SelectDialog(mContext);
			shareSelectDialog.setTitle("选择方式");
			shareSelectDialog.addItem("微信版邀请");
			shareSelectDialog.addItem("APP下载邀请");
			shareSelectDialog.setOnDialogItemClickListener(new SelectDialog.OnSelectDialogItemClickListener() {
				@Override
				public void onSelectItemClick(int position) {
					if(position == 0){
						if(qrCodeDialog == null){
							qrCodeDialog = new Dialog(mContext, R.style.custom_idalgo);
							qrCodeImg = new ImageView(mContext);
							qrCodeImg.setBackgroundColor(mContext.getResources().getColor(R.color.white));
							qrCodeImg.setScaleType(ImageView.ScaleType.FIT_CENTER);
							qrCodeDialog.setContentView(qrCodeImg);
							qrCodeImg.getLayoutParams().width = (int) (mContext.getResources().getDisplayMetrics().widthPixels*0.8);
							qrCodeImg.getLayoutParams().height = qrCodeImg.getLayoutParams().width;
						}
						QRCodeUtils.encodeAsBitmap("http://weixin.qq.com/r/XinWzh7EzkOxrVqt93xM", new QRCodeUtils.EncodeListener() {
							@Override
							public void encodeSuccedd(Bitmap qrCode) {
								qrCodeImg.setImageBitmap(qrCode);
								qrCodeDialog.show();
							}
							@Override
							public void encodeError(Throwable e) {
								qrCodeImg.setImageResource(R.mipmap.morentutouxiang);
								qrCodeDialog.show();
							}
						});
					} else if(position == 1){
						String url = SHARE_BASE_URL;
						if (inviteFriendsModel != null)
							url = inviteFriendsModel.getInvitationUrl();
						String shareContent = "邀请你加入广州创将。马上点击链接" + url
								+ "，下载app后通过微信或手机号登陆，团队成员都在等你了，点击链接快加入哦！";
						UserData userData = application.getUserData();
						if (userData != null)
							shareContent = userData.getUsername() + shareContent;
						if(shareBuilder == null) {
							shareBuilder = new ShareBuilder(getActivity());
							shareBuilder.withTitle(mContext.getResources().getString(R.string.app_name))
									.withMedia(new UMImage(mContext, R.mipmap.icon_launcher));
						}
						shareBuilder.withText(shareContent)
								.withCopyContent(url)
								.withTargetUrl(url)
								.withQRCodeUrl(url)
								.build().open();
					}
				}
			});
		}
		shareSelectDialog.show();
	}

	/* 查看网络请求日志 */
	private void showNetLog() {
		startActivity(new Intent(getContext(), NetLogActivity.class));
	}


	/**
	 * 创建背景view
	 *
	 * @param size
	 * @return
	 */
	private View createBackGroundView(int size) {
		View view = new View(mContext);
		view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, size));
		view.setBackgroundResource(R.color.gray_bg);
		return view;
	}

	/**
	 * 初始化消息栏
	 *
	 * @param list
	 */
	private void initDataRv(List<ActiveDataModel> list) {
		this.modelList = list;
		msgLayout.setLayoutManager(new LinearLayoutManager(
				mContext, LinearLayoutManager.HORIZONTAL, false));
		if (mDataAdapter == null) {
			mDataAdapter = new MyDataAdapter(mContext, list);

			mDataAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
				//                @Override
//                public void itemSelect(int position) {
//                    switch (position) {
//                        case 0:
//                            if (!application.isLogin()) {
//                                toLoginActivity();
//                            } else {
//                                startActivity(new Intent(mContext, MessageActivity.class));
//                            }
//                            break;
//                        case 1:
//                            startActivity(new Intent(mContext, CollectionActivity.class));
//                            break;
//                        case 2:
//                            if (!application.isLogin()) {
//                                toLoginActivity();
//                            } else {
//                                startActivity(new Intent(mContext, OrderActivity.class));
//                            }
//                        case 3://钱包
//                            if (!application.isLogin()) {
//                                toLoginActivity();
//                            } else {
//                                startActivity(new Intent(mContext, WalletActivity.class));
//                            }
//                            break;
//                        case 4:// 积分
//                            if (!application.isLogin()) {
//                                toLoginActivity();
//                            } else {
//                                startActivity(new Intent(mContext, IntegralActivity.class));
//                            }
//                            break;
//                        default:
//                            break;
//                    }
				@Override
				public void itemSelect(int position) {
					switch (position) {
						case 0:
							startActivity(new Intent(mContext, CollectionActivity.class));
							break;
						case 1:// 积分
							if (!application.isLogin())
								toLoginActivity();
							else
								startActivity(new Intent(mContext, IntegralActivity.class));
							break;
						case 2:
							if (!application.isLogin())
								toLoginActivity();
							else
								startActivity(new Intent(mContext, OrderActivity.class));
					}
				}
			});
			msgLayout.setAdapter(mDataAdapter);
		} else {
			mDataAdapter.updateAdapter(list);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.head_photo:
			case R.id.edit_info_btn://编辑中心去到个人档案
				if (!application.isLogin()) {
					toLoginActivity();
				} else {
					startActivityForResult(new Intent(mContext, UserSettingActivity.class), USER_DATA_SETTING);
				}
				break;
			case R.id.login_btn://登录按钮
				toLoginActivity();
				break;

			case R.id.vip_hlep://了解会员按钮
			case R.id.vip_btn://成为会员按钮
				/*if (!application.isLogin()) {
                    toLoginActivity();
                }*//* else if(userData.getIsVip() == 1){
                    startActivity(new Intent(mContext, VipActivity.class));
                } else {
                    startActivity(new Intent(mContext, VipBuyActivity.class).putExtra("vipLevel", 1));
                }*/
				startActivity(new Intent(mContext, VipActivity.class));
				break;
			case R.id.icon_serach:
				startActivity(new Intent(mContext, MessageDetailActivity.class)
						.putExtra("id", "4bd2a66a-d7cd-4948-9515-9923eef2e1e4")
						.putExtra("type", 1000));
				LatestStateService.clearSystemMsg();
				break;
			default:
				break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == EXIT_LOGIN_CODE && resultCode == EXIT_LOGIN_CODE) {
			isLogin = false;
			initUserData(isLogin);
			initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
		} else if (requestCode == LOGIN_CODE) {//登录成功
			initUserData(isLogin);
			initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
		} else if (requestCode == 10001 && resultCode == 10001) {//二维码返回
			String url = data.getStringExtra("url");
			ToasUtil.toast(mContext, url);
		} else if (requestCode == SWITCH_ORGANIZE_CODE && resultCode == RESULT_OK) {
			initUserData(isLogin);
			initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
		} else if (requestCode == USER_DATA_SETTING && resultCode == RESULT_OK) {
			initUserData(isLogin);
			initDataRv(mBusiness.getActiveData(getActiveIndex(true), application.getUserData()));
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		localBroadcastManager.unregisterReceiver(localBroadCast);
	}

	/**
	 * @return 假定用户活跃数据数据量
	 */
	private List<Integer> getActiveIndex(boolean isLogin) {
		List<Integer> index = new ArrayList<>();
//        index.add(isLogin&&userData!=null ? userData.getIntegralNum() : 0);         // 我的竞币
//        index.add(isLogin&&userData!=null ? userData.getBrowseNum() : 0);           // 我的足迹
//        index.add(isLogin&&userData!=null ? userData.getSubscribetNum() : 0);       // 关注数
//        index.add(isLogin&&userData!=null ? userData.getFollowNum() : 0);           // 收藏数
//        index.add(isLogin&&userData!=null ? userData.getSubjectNum() : 0);          // 主题数
//        index.add(isLogin&&userData!=null ? userData.getTopicNum() : 0);            // 话题数
//        index.add(isLogin&&userData!=null ? userData.getAdvicesNum() : 0);          // 报料数
//        index.add(isLogin&&userData!=null ? userData.getExpNum() : 0);              // 体验数
//        index.add(isLogin&&userData!=null ? userData.getShareNum() : 0);            // 分享数
		return index;
	}
}
